package com.lxl.hadoop.table;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author lixilin
 * @Date 2022/1/2 22:34
 * @Description
 */
public class TableReducer extends Reducer<Text,TableBean,TableBean, NullWritable> {

    List<TableBean> orderList;
    TableBean pdBean;
    String order = "order";
    NullWritable nullWritable = NullWritable.get();
    @Override
    protected void reduce(Text key, Iterable<TableBean> values, Context context) throws IOException, InterruptedException {

        orderList = new ArrayList<TableBean>();
        pdBean = new TableBean();
        for (TableBean value : values) {
            if (order.equals(value.getFlag())) {
                TableBean order = new TableBean();
                try {
                    BeanUtils.copyProperties(order,value);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
                orderList.add(order);
            } else {
                pdBean.setPname(value.getPname());
            }
        }

        for (TableBean bean : orderList) {
            bean.setPname(pdBean.getPname());
            context.write(bean,nullWritable);
        }
    }
}
